import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/user'
import router from '@/router'


// 创建axios实例
export const httpInstance = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  try {
    const userStore = useUserStore();
    const token = userStore.userInfo?.userInfoVO?.token
    if (token) {
      config.headers.Authorization = `Bearer ${userStore.userInfo.userInfoVO.token}`
    }
  } catch (e) {
    console.error('获取用户信息失败:', e);
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(
  res => {
    if (res.data.code && res.data.code !== 0) {
      ElMessage({
        type: 'warning',
        message: res.data.msg || '业务异常'
      })
      return Promise.reject(res.data)
    }
    return res.data
  },
  e => {
    console.log('请求错误:', e);

    if (e && e.response && e.response.status === 401) {
      //清除本地数据

    if(e.response && e.response.status === 401) {
      const userStore = useUserStore();
      userStore.clearUserInfo();
      router.push('/login')
    }
    return Promise.reject(e)
  }
})

export const get = (url, params = {}, config = {}) => {
  return httpInstance.get(url, { params, ...config })
}

export const post = (url, data = {}, config = {}) => {
  console.log('POST请求发送:', url, data)
  return httpInstance.post(url, data, config)
}

export const postForm = (url, data = {}, config = {}) => {
  // 将数据转换为 application/x-www-form-urlencoded 格式
  const formData = new URLSearchParams();
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      formData.append(key, data[key]);
    }
  }
  
  return httpInstance.post(url, formData, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    ...config
  });
}

export const put = (url, data = {}, config = {}) => {
  return httpInstance.put(url, data, config)
}

export const del = (url, config = {}) => {
  return httpInstance.delete(url, config)
}